import {message} from "@/utils/message";
import {transformI18n} from "@/plugins/i18n";
import forms, {type FormProps} from "../import.vue";
import AddForm from "../components/AddForm.vue";
import DetailForm from "../components/DetailForm.vue";
import TelConnectionEditForm from "../components/TelConnectionEditForm.vue";
import type {PaginationProps} from "@pureadmin/table";
import {getKeyList} from "@pureadmin/utils";
import {getSalesList} from "@/api/crm";
import {onMounted, reactive, ref, type Ref, toRaw, h} from "vue";
import {addDrawer} from "@/components/ReDrawer/index";
import {importPerformanceList, performanceController, updatePerformanceTelConnection} from "@/api/system";

export function useAccount(tableRef: Ref) {
  const form = reactive({
    name: "",
    code: "",
    audit_status: "3",
    email: "",
  });
  const curRow = ref();
  const dataList = ref([]);
  const customerTypeArr = ref([]);
  const customerSourceArr = ref([]);
  const statusList = ref([]);
  const selectedNum = ref(0);
  const isShow = ref(false);
  const loading = ref(true);
  const isLinkage = ref(false);
  const isExpandAll = ref(false);
  const isSelectAll = ref(false);
  const salesman_arr = ref([]);
  const original_salesman_arr = ref([]); // 新增原归属人列表
  const template_url = ref('');
  const paymentChannelOptions = ref([]);
  const currencyOptions = ref([]);
  const telConnectionOptions = ref([]); // 电联员工选项
  const paymentVerifiedStatusOptions = ref([]); // 到账状态选项


  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,pageSizes: [20, 40, 60,100,300,500],
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    { label: "勾选列", type: "selection", fixed: "left",width: 50,},
    { label: "id", prop: "id", width: 60, align: "left"},
    { label: "成单日期", prop: "pay_at",width:120,showOverflowTooltip:true,},
    { label: "业务员", prop: "sales.username", width: 80},
    {label: "小组", prop: "sales.dept.department_name", width: 70},
    { label: "原归属人", prop: "original_own_id", width: 80,
      formatter: (row) => {
        return getOriginalOwnerName(row.original_own_id)
      }
    },
    {label: "sa", prop: "sa", width: 100},
    {label: "客户类型", prop: "customer_type", width: 140},
    {label: "客户来源", prop: "customer_source", width: 140},
    
    { label: "邮箱", prop: "email",width: 200,showOverflowTooltip:true,},
    { label: "payment channel", prop: "payment_channel", width: 150},
    { label: "原始金额", prop: "original_order_fee", width: 150,
      formatter: (row) => {
        return `${row.original_order_fee || ''} ${row.original_currency || ''}`.trim()
      }
    },
    { label: "订单原金额", prop: "order_fee", width: 150},
    { label: "备注", prop: "remark", width: 150},
    { label: "收款账号", prop: "ta", width: 150},
    { label: "流水号", prop: "pr", width: 150},
    { label: "到账状态", prop: "payment_verified_status", width: 120,
      formatter: (row) => {
        return getPaymentVerifiedStatusName(row.payment_verified_status)
      }
    },
    { label: "到账备注", prop: "payment_verified_remark", width: 150},
    { label: "数据来源", prop: "sources_remark", width: 150},
    { label: "电联", prop: "tel_connection_id", width: 150,
      formatter: (row) => {
        return getTelConnectionName(row.tel_connection_id)
      }
    },
    { label: "shop", prop: "shop", width: 150},
    { label: "是否短信成单", prop: "is_sms", width: 150,
      formatter: (row) => {
        return `${row.is_sms?'短信成单':'否'} `.trim()
      }
    },
    {label: "最低售价超额", prop: "exceed_remark", width: 140},
    {label: "帮扶人", prop: "help_remark", width: 140},
    {label: "上传时间", prop: "created_at", width: 140},
    {label: "操作", fixed: "right", width: 200, slot: "operation"}
  ];


  function handleDelete(row) {
    performanceController(row, "delete").then(res => chores(row, res, '删除', onSearch))
  }
  //录入业绩
  function openAddDialog() {
    let formRef;
    let formData = null;

    addDrawer({
      size: "60%",
      title: "录入业绩",
      contentRenderer: () => h(AddForm, {
        ref: (el) => { formRef = el; },
        salesOptions: salesman_arr.value.map(item => ({ label: item.dept?item.dept.name+'-'+item.username:item.username, value: item.id })),
        originalSalesOptions: original_salesman_arr.value.map(item => ({ label: item.dept?item.dept.department_name+'-'+item.username:item.username, value: item.id })),
        customerTypeOptions: customerTypeArr.value,
        customerSourceOptions: customerSourceArr.value,
        paymentChannelOptions: paymentChannelOptions.value,
        currencyOptions: currencyOptions.value,
        telConnectionOptions: telConnectionOptions.value,
        paymentVerifiedStatusOptions: paymentVerifiedStatusOptions.value,
        onSubmit: (data) => {
          formData = data;
        }
      }),
      closeOnClickModal: false,
      sureBtnLoading: true,
      beforeSure: (done, { options, closeLoading }) => {
        if (formRef && formRef.validateForm) {
          formRef.validateForm().then(() => {
            if (formData) {
              performanceController(formData, 'post').then(res => {
                if (res.code === 0) {
                  message("录入成功", { type: "success" });
                  done();
                  onSearch();
                } else {
                  message(`录入失败：${res.message}`, { type: "error" });
                }
                closeLoading();
              }).catch(() => {
                closeLoading();
              });
            } else {
              closeLoading();
            }
          }).catch(() => {
            closeLoading();
          });
        } else {
          message("表单验证组件未找到", { type: "error" });
          closeLoading();
        }
      }
    });
  }

  //查看详情
  function openDetailDialog(row) {
    addDrawer({
      size: "60%",
      title: "业绩详情",
      contentRenderer: () => h(DetailForm, {
        detail: row,
        salesOptions: salesman_arr.value.map(item => ({ label: item.dept?item.dept.name+'-'+item.username:item.username, value: item.id })),
        originalSalesOptions: original_salesman_arr.value.map(item => ({ label: item.dept?item.dept.department_name+'-'+item.username:item.username, value: item.id })),
        customerTypeOptions: customerTypeArr.value,
        customerSourceOptions: customerSourceArr.value,
        telConnectionOptions: telConnectionOptions.value
      }),
      closeOnClickModal: false
    });
  }

  //编辑业绩
  function openEditDialog(row) {
    let formRef;
    let formData = null;

    addDrawer({
      size: "60%",
      title: "编辑业绩",
      contentRenderer: () => h(AddForm, {
        ref: (el) => { formRef = el; },
        isEdit: true,
        editData: row,
        salesOptions: salesman_arr.value.map(item => ({ label: item.dept?item.dept.name+'-'+item.username:item.username, value: item.id })),
        originalSalesOptions: original_salesman_arr.value.map(item => ({ label: item.dept?item.dept.department_name+'-'+item.username:item.username, value: item.id })),
        customerTypeOptions: customerTypeArr.value,
        customerSourceOptions: customerSourceArr.value,
        paymentChannelOptions: paymentChannelOptions.value,
        currencyOptions: currencyOptions.value,
        telConnectionOptions: telConnectionOptions.value,
        paymentVerifiedStatusOptions: paymentVerifiedStatusOptions.value,
        onSubmit: (data) => {
          formData = data;
        }
      }),
      closeOnClickModal: false,
      sureBtnLoading: true,
      beforeSure: (done, { options, closeLoading }) => {
        if (formRef && formRef.validateForm) {
          formRef.validateForm().then(() => {
            if (formData) {
              // 使用PUT方法更新数据
              performanceController({...formData, id: row.id}, "put").then(res => {
                if (res.code === 0) {
                  message("更新成功", { type: "success" });
                  done();
                  onSearch();
                } else {
                  message(`更新失败：${res.message}`, { type: "error" });
                }
                closeLoading();
              }).catch(() => {
                closeLoading();
              });
            } else {
              closeLoading();
            }
          }).catch(() => {
            closeLoading();
          });
        } else {
          message("表单验证组件未找到", { type: "error" });
          closeLoading();
        }
      }
    });
  }

  //修改电联
  function openTelConnectionEditDialog(row) {
    let formRef;
    let formData = null;

    addDrawer({
      size: "40%",
      title: "修改电联",
      contentRenderer: () => h(TelConnectionEditForm, {
        ref: (el) => { formRef = el; },
        currentValue: row.tel_connection_id,
        telConnectionOptions: telConnectionOptions.value,
        onSubmit: (data) => {
          formData = data;
        }
      }),
      closeOnClickModal: false,
      sureBtnLoading: true,
      beforeSure: (done, { options, closeLoading }) => {
        if (formRef && formRef.validateForm) {
          formRef.validateForm().then(() => {
            if (formData !== null) {
              // 只更新电联字段
              updatePerformanceTelConnection(row.id, {
                tel_connection_id: formData.tel_connection_id
              }).then(res => {
                if (res.code === 0) {
                  message("电联修改成功", { type: "success" });
                  done();
                  onSearch();
                } else {
                  message(`修改失败：${res.message}`, { type: "error" });
                }
                closeLoading();
              }).catch(() => {
                closeLoading();
              });
            } else {
              message("表单数据未找到", { type: "error" });
              closeLoading();
            }
          }).catch(() => {
            closeLoading();
          });
        } else {
          message("表单验证组件未找到", { type: "error" });
          closeLoading();
        }
      }
    });
  }

  //导入数据
  function importData() {
    addDrawer({
      size: "55%",
      title: "导入业绩",
      contentRenderer: () => forms,
      props: {
        formInline: {
          template_url: template_url.value,
          dataList:[[]],
          // export_field:export_field,
          // id:row.id,
          checkCond:[salesman_arr.value,customerTypeArr.value,customerSourceArr.value]
        }
      },
      closeOnClickModal: false,
      sureBtnLoading: true,
      beforeSure: (done, { options, index,closeLoading }) => {
        const { formInline } = options.props as FormProps;
        if(formInline.dataList.length == 0){
          message(`你没有导入数据`, { type: "error" });
          closeLoading();
        }else if(formInline.dataList.filter(x=>x["状态检查"]!="数据检查正常").length > 0){
          const errorNum = formInline.dataList.filter(x=>x["状态检查"]!="数据检查正常").length;
          message(`您导入的数据有${errorNum}条文件格式错误，请改正后重新上传`, { type: "error" });
          closeLoading();
        }else{
          importPerformanceList({list:formInline.dataList},"post").then(res=>{
            if(res.code==0){
              onSearch()
              if(res.data.filter(x=>x.i_status!='ok').length==0){//全部成功的关闭
                done();
                message(`已成功导入${res.data.filter(x=>x.i_status=='ok').length}条`, {
                  type: "success"
                });
              }else{
                formInline.dataList = formInline.dataList.map((da,idx) => ({
                  ...da,
                  '状态检查': res.data[idx]?.i_status||''
                }));
                message(`已成功导入${res.data.filter(x=>x.i_status=='ok').length}条,失败${res.data.filter(x=>x.i_status!='ok').length}条`, {
                  type: "warning"
                });
              }
            }else{
              formInline.dataList = []
              message(`导入失败,失败原因：`+res.message, {
                type: "error"
              });
            }
            closeLoading();
          })
        }
        // done(); // 需要关闭把注释解开即可
      },
    });
  }

  const getOriginalOwnerName = (ownerId: number | undefined) => {
    if (!ownerId) return '-';
    const salesOptions = original_salesman_arr.value.map(item => ({
      label: item.dept ? item.dept.department_name + '-' + item.username : item.username,
      value: item.id
    }))
    const owner = salesOptions.find(item => item.value === ownerId);
    return owner?.label || '-';
  };

  const getTelConnectionName = (telConnectionId: number | undefined) => {
    if (!telConnectionId) return '-';
    const telConnection = telConnectionOptions.value.find(item => item.id === telConnectionId);
    return telConnection?.nickname || telConnection?.username || '-';
  };

  const getPaymentVerifiedStatusName = (status: number | undefined) => {
    if (status === undefined) return '-';
    switch (status) {
      case 0:
        return '待确定';
      case 1:
        return '已到账';
      case 2:
        return '未到账';
      case 3:
        return '部分到账';
      default:
        return '-';
    }
  };

  function handleSizeChange(val: number) {
    pagination.pageSize = val
    onSearch()
  }
  const getSalemanList = async function (page=1,limit=1000) {
    const {data} = await getSalesList({page,limit}); // 这里是返回一维数组结构，前端自行处理成树结构，返回格式要求：唯一id加父节点parentId，parentId取父节点id
    salesman_arr.value = data?.data;
  }
  function handleCurrentChange(val: number) {
    pagination.currentPage = val
    onSearch()
  }

  async function onSearch() {
    loading.value = true;
    form.page = pagination.currentPage
    form.limit = pagination.pageSize
    const {data} = await performanceController(toRaw(form), 'get');
    dataList.value = data.data;
    customerTypeArr.value = data.customer_type_arr;
    customerSourceArr.value = data.customer_source_arr;
    statusList.value = data.status_arr;
    template_url.value = data.template_url;
    searchCondList.value = data?.search_cond_arr;
    paymentChannelOptions.value = data.payment_channel_arr || [];
    currencyOptions.value = data.currency_arr || [];
    original_salesman_arr.value = data.original_salesman_arr || []; // 新增获取原归属人数据
    telConnectionOptions.value = data.tel_connection_arr || []; // 新增获取电联员工数据
    paymentVerifiedStatusOptions.value = data.payment_verified_status_arr || []; // 新增获取到账状态数据
    pagination.total = data.total;
    pagination.pageSize = data.per_page;
    pagination.currentPage = data.current_page;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function chores(curData, res, title, done) {
    if (res.code === 0) {
      message(`您${title}了邮箱为${curData.email}的这条数据`, {type: "success"});
      done(); // 关闭弹框
      onSearch(); // 刷新表格数据
    } else {
      message(`${title}失败，原因：${res.message}`, { type: "error"});
    }
  }



  /** 数据权限 可自行开发 */
  const searchCondList =  ref([])

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
  }

  /** 批量删除 */
  function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    performanceController({id:getKeyList(curSelected, "id")},"delete").then(res=>{
      if(res.code==0){
        message(`已删除id为 ${getKeyList(curSelected, "id")} 的数据`, {
          type: "success"
        });
        tableRef.value.getTableRef().clearSelection();
        onSearch();
      }else{
        message(`删除失败,失败原因：`+res.message, {
          type: "error"
        });
      }

    })
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    tableRef.value.getTableRef().clearSelection();
  }
  const isEmpty = (obj) => Object.keys(obj).length === 0 && obj.constructor === Object;


  const filterMethod = (query: string, node) => {
    return transformI18n(node.title)!.includes(query);
  };

  onMounted(async () => {
    onSearch();
    getSalemanList();
  });


  return {
    form, isShow, curRow, loading, columns, dataList, isLinkage, pagination, isExpandAll, isSelectAll,importData,
    selectedNum,onSelectionCancel,handleSelectionChange,
    statusList,salesman_arr,original_salesman_arr,onbatchDel,
    onSearch, resetForm,
    searchCondList,
    handleDelete, filterMethod, transformI18n, handleSizeChange,
    handleCurrentChange,customerTypeArr,customerSourceArr,openAddDialog,paymentChannelOptions,currencyOptions,telConnectionOptions,openDetailDialog,openEditDialog,openTelConnectionEditDialog,
    paymentVerifiedStatusOptions,
  };
}
